<script setup lang="ts">
import { ref, onMounted, defineComponent, h } from "vue"
import { ElCollapse, ElCollapseItem, ElSkeleton, ElSkeletonItem } from "element-plus"
import { DocumentViewer, VideoViewer } from "./modules"
import { getCourseDirectoryApi, getCourseDetailApi } from '#/api/manage/course'
import { useRouter } from 'vue-router'
import { $t } from '@vben/locales'

const router = useRouter();

// 内容类型枚举
enum ContentType {
  DOCUMENT = 'document',
  VIDEO = 'video'
}

let menuName = ref<string[]>([]) // 改为数组支持多个展开节点
let selectedItem = ref<any>({}) // 默认选中第一章
const lessonMenu = ref<any[]>([])
const basicInfo = ref<any>({})
const menuLoading = ref(true) // 菜单加载状态

// 判断内容类型
const getContentType = (item: any): ContentType => {
  return item.contentType || ContentType.DOCUMENT;
}

const loadPDF = (item: any) => {
  selectedItem.value = item
  expandToNode(item)
}

// 递归查找第一个可选中的节点（没有子节点的节点）
const findFirstSelectableNode = (items: any[]): any => {
  for (const item of items) {
    const hasChildren = item.content && Array.isArray(item.content) && item.content.length > 0
    if (!hasChildren) {
      return item
    } else {
      const selectableChild = findFirstSelectableNode(item.content)
      if (selectableChild) {
        return selectableChild
      }
    }
  }
  return null
}

// 递归查找节点的所有父级路径
const findNodePath = (items: any[], targetNode: any, currentPath: string[] = []): string[] | null => {
  for (const item of items) {
    const newPath = [...currentPath, item.id || item.name]
    const hasChildren = item.content && Array.isArray(item.content) && item.content.length > 0

    if (!hasChildren && item === targetNode) {
      return newPath.slice(0, -1) // 排除自身，只返回父级路径
    } else if (hasChildren) {
      const foundPath = findNodePath(item.content, targetNode, newPath)
      if (foundPath) {
        return foundPath
      }
    }
  }
  return null
}

// 展开到指定节点的所有父级
const expandToNode = (targetNode: any) => {
  const path = findNodePath(lessonMenu.value, targetNode)
  if (path) {
    menuName.value = path
  }
}

const getCourseDirectory = async () => {
  try {
    menuLoading.value = true
    const courseId = router.currentRoute.value.params.id as string
    const data = await getCourseDirectoryApi(courseId)
    lessonMenu.value = data.map((item: any) => ({
      ...item,
      content: JSON.parse(item.content)
    }))

    // 自动选中第一个可选择的节点并展开所有父级
    const firstSelectableNode = findFirstSelectableNode(lessonMenu.value)
    if (firstSelectableNode) {
      selectedItem.value = firstSelectableNode
      expandToNode(firstSelectableNode)
    }
  } finally {
    menuLoading.value = false
  }
}

const getCourseDetail = async () => {
  const courseId = router.currentRoute.value.params.id as string
  const data = await getCourseDetailApi(courseId)
  basicInfo.value = data
}

// 递归渲染菜单项的组件
const MenuItemRecursive = defineComponent({
  name: 'MenuItemRecursive',
  props: {
    items: Array,
    level: {
      type: Number,
      default: 0
    }
  },
  setup(props) {
    const renderMenuItem = (item: any, level: number) => {
      const hasChildren = item.content && Array.isArray(item.content) && item.content.length > 0
      const paddingLeft = level * 15 + 'px'

      if (hasChildren) {
        return h(ElCollapse, {
          modelValue: menuName.value,
          'onUpdate:modelValue': (val: any) => {
            menuName.value = val
          },
          class: 'border-t-[0px]',
          style: 'border-top:0px'
        }, () => [
          h(ElCollapseItem, {
            name: item.id || item.name
          }, {
            title: () => h('div', { style: { paddingLeft } }, item.name),
            default: () => item.content.map((child: any) => renderMenuItem(child, level + 1))
          })
        ])
      } else {
        return h('div', {
          class: [
            'cursor-pointer py-[8px] rounded-[4px] transition-colors duration-200 select-item',
            selectedItem.value.name === item.name ? 'selected' : ''
          ],
          style: { paddingLeft },
          onClick: () => loadPDF(item)
        }, item.name)
      }
    }

    return () => props.items?.map((item: any) => renderMenuItem(item, props.level))
  }
})

onMounted(() => {
  getCourseDetail()
  getCourseDirectory()
})
</script>

<template>
  <div class="h-[90px] flex flex-col pr-[20px] min-h-[1px] overflow-hidden">
    <div class="container top bg-color pt-[20px] pb-[20px] pl-[35px] pr-[30px] text-[25px] font-[600] mb-[10px]">
      {{ basicInfo?.name }}
    </div>
    <div class="container bg-color flex-1 min-h-[1px] flex bg-[#f4f5f5] p-[0px]">
      <div class="left w-[33%] border-r border-pure overflow-auto">
        <div class="title lesson-title">{{ $t('lesson.courseOutline') }}</div>
        <div class="menu pl-[45px] pr-[20px] py-3 text-[14px]">
          <!-- 加载时显示骨架屏 -->
          <ElSkeleton v-if="menuLoading" :loading="menuLoading" animated>
            <template #template>
              <div class="skeleton-menu">
                <!-- 第一级菜单项骨架 -->
                <div v-for="i in 3" :key="i" class="mb-4">
                  <ElSkeletonItem variant="text" style="width: 80%; height: 24px; margin-bottom: 8px;" />
                  <!-- 子菜单项骨架 -->
                  <div class="ml-4">
                    <ElSkeletonItem variant="text" style="width: 70%; height: 20px; margin-bottom: 6px;" />
                    <ElSkeletonItem variant="text" style="width: 65%; height: 20px; margin-bottom: 6px;" />
                    <ElSkeletonItem variant="text" style="width: 75%; height: 20px;" />
                  </div>
                </div>
              </div>
            </template>
          </ElSkeleton>
          <!-- 加载完成后显示菜单 -->
          <MenuItemRecursive v-else :items="lessonMenu" :level="0" />
        </div>
      </div>
      <div class="right min-w-[1px] flex-1 bg-[#f4f5f5]">
        <!-- 根据内容类型渲染不同的预览组件 -->
        <DocumentViewer v-if="getContentType(selectedItem) === ContentType.DOCUMENT" :path="selectedItem.path" />
        <VideoViewer v-else-if="getContentType(selectedItem) === ContentType.VIDEO" 
          :path="selectedItem.path" 
          :vodAssetId="selectedItem.vodAssetId" />
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.bg-color {
  background: #fff;
}

.lesson-title {
  padding: 15px 15px 15px 40px;
  border-bottom: 1px solid hsl(var(--border));
  font-size: 17px;
  font-weight: 500;
}

.text-show {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-collapse-item__content {
  padding-bottom: 10px;
}

:deep(.select-item) {
  margin: 2px 0;
  padding-left: 10px;
  padding-right: 10px;
}

:deep(.select-item:hover) {
  background-color: #f0f0f0;
}

:deep(.select-item.selected) {
  color: var(--el-color-primary);
  font-weight: 600;
  //background-color: #e6f4ff;
}

/* 骨架屏样式 */
.skeleton-menu {
  padding: 8px 0;
}

:deep(.el-skeleton__item) {
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 400% 100%;
  animation: loading 1.5s ease infinite;
}

@keyframes loading {
  0% {
    background-position: 100% 50%;
  }

  100% {
    background-position: -100% 50%;
  }
}
</style>
